<template>
  <div class="add-box">
    <div class="permiss-box">
      <el-form
        ref="roleForm"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="dataRangeId">
          <el-select
            v-model="formData.dataRangeId"
            placeholder="请选择角色"
            :style="{ width: '70%' }"
            @change="changeRole"
          >
            <el-option
              v-for="(item, index) in roleList"
              :key="index"
              :label="item.rangeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="permiss-box data-limit-box">
      <span class="title">数据权限预览</span>
      <div class="limit-select">
        <span class="title limit-title">权限范围</span>
        <el-select
          v-model="formData.rangeLevel"
          :disabled="true"
          placeholder="请选择数据权限"
          :style="{ width: '70%' }"
        >
          <el-option
            v-for="(item, index) in dictOptions[
              'ecp-admin.dataRange.rangeLevel'
            ]"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div
        v-loading="permissLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 1)"
        class="content"
        style="overflow: auto;"
      >
        <el-tree
          ref="permissTreeRef"
          :data="sceneIdList"
          node-key="value"
          :default-expand-all="true"
          :props="{ children: 'children', label: 'label' }"
          highlight-current
        />
      </div>
    </div>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import { parseSceneDataProject, convertToTree } from '@/utils/scene-data'
import { elementMixin } from '@/mixin/element'
import userManage from '@/api/apis/userManage'

export default {
  name: 'UserDataRole',
  mixins: [dictMixin, elementMixin],
  props: {
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        dataRangeId: '',
        rangeLevel: 'all'
      },
      // 菜单权限参数
      loading: false,
      permissLoading: false,
      deptDefaultChecked: [],
      roleList: [],
      sceneIdList: [],
      rules: {
        dataRangeId: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      dictCode: ['ecp-admin.dataRange.rangeLevel']
    }
  },
  watch: {
    popData: {
      handler(data) {
        if (data) {
          let formFields = []
          if (this.popConfig.popType === 'edit') {
            formFields = ['dataRangeId', 'rangeCode', 'remark', 'status']
          } else {
            formFields = []
          }
          for (const key in this.popData) {
            if (
              Object.hasOwnProperty.call(this.popData, key) &&
              formFields.includes(key)
            ) {
              this.$set(this.formData, key, this.popData[key])
            }
          }
        }
        const { dataRangeId } = this.popData || {}
        this.getAuthData(dataRangeId)
      },
      deep: true,
      immediate: true
    },
    confirm: {
      handler(confirm) {
        this.submit()
      }
    }
  },
  created() {
    this.queryAllRoleList()
  },
  methods: {
    async queryAllRoleList() {
      try {
        const res = await this.$api.dataRange.queryAllList({})
        if (res.code === '1000') {
          this.roleList = res.data || []
        }
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * 提交
     */
    submit() {
      this.$refs.roleForm.validate(async (valid) => {
        if (valid) {
          const { dataRangeId } = this.formData
          const res = await this.$api.userManage.allotDataRangeRole({
            dataRangeId,
            id: this.popData.id
          })
          if (Number(res.code) === 1000) {
            this.$message.success('分配成功!')
            this.$emit('onFinish', 'user-allot-rangerole')
          }
        } else {
          return false
        }
      })
    },
    // 获取用户权限信息
    async getAuthData(id) {
      if (!id) {
        this.sceneIdList = []
        return
      }
      const params = {
        id
      }
      this.loading = true
      try {
        const res = await this.$api.dataRange.detail(params)
        if (res.code === '1000') {
          const { sceneIdList = [], rangeLevel } = res.data || {}
          const formFields = [
            'dataRangeId',
            'rangeCode',
            'remark',
            'status',
            'rangeLevel'
          ]
          for (const key in res.data) {
            if (
              Object.hasOwnProperty.call(res.data, key) &&
              formFields.includes(key)
            ) {
              this.$set(this.formData, key, res.data[key])
            }
          }
          this.changeLevel(rangeLevel, sceneIdList)
        }
        this.loading = false
      } catch (error) {
        console.log(error)
        this.loading = false
      }
    },
    changeRole(id) {
      if (!id) {
        this.sceneIdList = []
        return
      }
      this.getAuthData(id)
    },
    // 数据权限范围
    async changeLevel(e, sceneIdList) {
      if (!e) return
      try {
        if (e === 'all') {
          this.sceneIdList = []
          return
        }
        this.loading = true
        const res = await this.$api.dataRange.querySceneList({
          id: e
        })
        if (res.code === '1000') {
          let arrTree = []
          let newData = []
          if (sceneIdList && sceneIdList.length) {
            arrTree = this.handlerShowData(res.data, sceneIdList) || []
          }
          newData = sceneIdList && sceneIdList.length ? arrTree : (res.data || [])
          switch (e) {
            case 'project':
              arrTree = newData.map((e) => {
                return {
                  ...e,
                  label: e.projectName,
                  value: e.sceneProjectId,
                  type: 'project'
                }
              })
              break
            case 'company':
              arrTree = convertToTree(newData)
              break

            default:
              arrTree = parseSceneDataProject(newData)
              break
          }
          this.sceneIdList = arrTree || []
        }
        this.loading = false
      } catch (error) {
        this.loading = false
        console.log(error)
      }
    },
    // 处理数据
    handlerShowData(dataList, sceneIdList) {
      if (!dataList || !dataList.length) return
      const newData = dataList.filter((e) => {
        return (
          sceneIdList.includes(e.sceneProjectId) ||
          sceneIdList.includes(e.sceneEdificeId) ||
          sceneIdList.includes(e.sceneFloorId) ||
          sceneIdList.includes(e.id) ||
          sceneIdList.includes(e.companyId)
        )
      })
      return newData || []
    }
  }
}
</script>

<style lang="scss" scoped>
.add-box {
  color: #333;
  display: flex;
  max-height: 50vh;
  border: 1px solid #e7e7e7;

  .permiss-box {
    display: flex;
    flex-direction: column;
    padding: 14px;
    width: 50%;
    &.data-limit-box {
      border-left: 1px solid #e7e7e7;
    }
    .title {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
    }
    .el-form {
      margin-top: 16px;
    }
  }
  .menu-info {
    margin-top: 14px;
    flex: 1;
    overflow-y: auto;
  }

  .data-info {
    margin-top: 14px;
    flex: 1;
    overflow-y: auto;
  }

  .limit-select {
    margin-top: 14px;
  }

  .limit-title {
    margin-right: 14px;
  }
}
</style>
